
#include "LedBlink.h"

LedBlink::LedBlink(int ledPin)
{
  pinMode(ledPin, OUTPUT);
  _enabled = false;
  _ledPin = ledPin;
}

//starts a timer that will blink the led without using delay().
//The update() method must be called in the loop method for it to work.
void LedBlink::startBlink(long interv, long blinkTime)
{
  _interval = interv;
  _totalBlinkTime = blinkTime;
  _enabled = true;
  _ledState = HIGH;
  _lastLedStateChangeTime = millis();
  _startTime = millis();
  setLedStateAndWriteValue(HIGH);
  
  Serial.println("Starting the blinker with interval = " + String(interv) + ", totalBlinkTime = " + String(blinkTime));
}

void LedBlink::stopBlink()
{
  _enabled = false;
  setLedStateAndWriteValue(LOW);
}

//Will change the state of the LED if enough time has passed since the last change of state.  Else do nothing.
int LedBlink::update()
{
  if(_enabled && millis() - _startTime >= _totalBlinkTime)
  {
    _enabled = false;
    setLedStateAndWriteValue(LOW);
    Serial.println("ledBlink::update() blinkTime finished, stopping blinking");
    return 0;
  }
  
  if(_enabled && millis() - _lastLedStateChangeTime >= _interval)
  {
    if(_ledState == LOW)
      setLedStateAndWriteValue(HIGH);
    else
      setLedStateAndWriteValue(LOW);
    
    _lastLedStateChangeTime = millis();
  }
  return 1;
}

void LedBlink::setLedStateAndWriteValue(int state)
{
  _ledState = state;
  digitalWrite(_ledPin, _ledState);
}

